package leetcode.practice;

/**
 * 19. 删除链表的倒数第 N 个结点
 */
public class RemoveNthFromEnd {

    public static void main(String[] args) {


    }

    public ListNode removeKLinkedList(ListNode head, int n) {
        if (head == null) {
            return head;
        }
        int length = 0;
        ListNode cur = head;
        while (cur != null) {
            cur = cur.next;
            length++;
        }

        // 如果删除的是首先节点
        if (n == length) {
            head = head.next;
            return head;
        }
        ListNode leftEnd = head;

        // 删除的正数第numK个节点
        int numK = length - n + 1;
        // 将第preK个节点的下一个节点删掉就行了
        int preK = numK - 1;

        // 第一个到底preK个要遍历preK-1步
        while (preK > 1) {
            leftEnd = leftEnd.next;
            preK--;
        }

        // 删除leftEnd的下一个节点
        if (leftEnd.next != null) {
            leftEnd.next = leftEnd.next.next;
        } else {
            leftEnd.next = null;
        }
        return head;
    }

    class ListNode {
        int val;
        ListNode next;
    }
}
